/*
 * Copyright (C) 2019 ByteDance Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bytedance.scene.ui;

import com.bytedance.scene.Scope;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionManager;
import ohos.aafwk.ability.fraction.FractionScheduler;
import ohos.aafwk.content.Intent;

import java.util.Optional;

public class ScopeHolderCompatFragment extends Fraction implements Scope.RootScopeFactory {
    private static final String TAG = "ScopeHolderCompatFragment";
    private final Scope mRootScope = Scope.DEFAULT_ROOT_SCOPE_FACTORY.getRootScope();

    private static ScopeHolderCompatFragment newInstance() {
        return new ScopeHolderCompatFragment();
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
    }

    public static ScopeHolderCompatFragment install(Fraction fraction, String tag, boolean forceCreate, boolean immediate) {
        String fragmentTag = tag + "_" + TAG;
        FractionManager fragmentManager = fraction.getFractionAbility().getFractionManager();
        Optional<Fraction> optionalFraction = fragmentManager.getFractionByTag(fragmentTag);
        ScopeHolderCompatFragment holderFragment = null;
        if (optionalFraction.isPresent()) {
            holderFragment = (ScopeHolderCompatFragment) optionalFraction.get();
        }
        if (holderFragment != null && forceCreate) {
            FractionScheduler transaction = fragmentManager.startFractionScheduler();
            transaction.remove(holderFragment);
            FragmentUtility.commitFragment(transaction, immediate);
            holderFragment = null;
        }

        if (holderFragment == null) {
            holderFragment = ScopeHolderCompatFragment.newInstance();
            FractionScheduler transaction = fragmentManager.startFractionScheduler();
            transaction.add(1, holderFragment, fragmentTag);
            FragmentUtility.commitFragment(transaction, immediate);
        }

        return ScopeHolderCompatFragment.newInstance();
    }


    @Override
    public Scope getRootScope() {
        return mRootScope;
    }
}